package com.szgz.platform.handler;

import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedTypes;
import com.szgz.platform.model.UserEnvironment.EnvironmentType;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Arrays;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 环境类型集合的类型处理器
 * 用于在数据库JSON和Java Set<EnvironmentType>之间转换
 */
@MappedTypes(Set.class)
public class EnvironmentTypeTypeHandler extends BaseTypeHandler<Set<EnvironmentType>> {

    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, Set<EnvironmentType> parameter, JdbcType jdbcType) throws SQLException {
        if (parameter != null && !parameter.isEmpty()) {
            // 转换为JSON数组格式: ["IDE", "JUPYTER"]
            String jsonArray = parameter.stream()
                    .map(EnvironmentType::name)
                    .map(name -> "\"" + name + "\"")
                    .collect(Collectors.joining(",", "[", "]"));
            ps.setString(i, jsonArray);
        } else {
            ps.setString(i, "[]");
        }
    }

    @Override
    public Set<EnvironmentType> getNullableResult(ResultSet rs, String columnName) throws SQLException {
        String value = rs.getString(columnName);
        return parseEnvironmentTypes(value);
    }

    @Override
    public Set<EnvironmentType> getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        String value = rs.getString(columnIndex);
        return parseEnvironmentTypes(value);
    }

    @Override
    public Set<EnvironmentType> getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        String value = cs.getString(columnIndex);
        return parseEnvironmentTypes(value);
    }

    private Set<EnvironmentType> parseEnvironmentTypes(String value) {
        if (value == null || value.trim().isEmpty() || value.equals("[]")) {
            return Set.of();
        }
        
        try {
            // 处理JSON数组格式: ["IDE", "JUPYTER"]
            String cleanValue = value.trim();
            if (cleanValue.startsWith("[") && cleanValue.endsWith("]")) {
                cleanValue = cleanValue.substring(1, cleanValue.length() - 1);
            }
            
            if (cleanValue.isEmpty()) {
                return Set.of();
            }
            
            return Arrays.stream(cleanValue.split(","))
                    .map(String::trim)
                    .map(s -> s.replace("\"", "").replace("'", ""))
                    .filter(s -> !s.isEmpty())
                    .map(EnvironmentType::valueOf)
                    .collect(Collectors.toSet());
        } catch (Exception e) {
            // 如果JSON解析失败，尝试旧的逗号分隔格式作为兼容
            return Arrays.stream(value.split(","))
                    .map(String::trim)
                    .filter(s -> !s.isEmpty())
                    .map(EnvironmentType::valueOf)
                    .collect(Collectors.toSet());
        }
    }
} 